<?php
namespace app\lawcase\controller;

use app\base\BaseController;
use app\lawcase\model\CaseDoc as CaseDocModel;
use app\lawcase\validate\CaseDocCheck;
use think\exception\ValidateException;
use think\facade\View;
use think\facade\Request;

/**
 * 案件文档管理控制器
 */
class CaseDoc extends BaseController
{
    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new CaseDocModel();
    }

    /**
     * 文档列表
     */
    public function index()
    {
        if (Request::isAjax()) {
            $param = get_params();
            $where = [];
            if (!empty($param['keywords'])) {
                $where[] = ['title', 'like', '%' . $param['keywords'] . '%'];
            }
            if (!empty($param['case_code'])) {
                $where[] = ['case_code', 'like', '%' . $param['case_code'] . '%'];
            }
            if (!empty($param['doc_type'])) {
                $where[] = ['doc_type', '=', $param['doc_type']];
            }
            $list = $this->model->getList($where, $param);
            return to_assign(0, '', $list);
        }
        return view();
    }

    /**
     * 添加文档
     */
    public function add()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $param['upload_uid'] = $this->uid;
            try {
                validate(CaseDocCheck::class)->check($param);
                $this->model->add($param);
            } catch (ValidateException $e) {
                return to_assign(1, $e->getError());
            }
        } else {
            View::assign([
                'id' => 0
            ]);
            return view();
        }
    }

    /**
     * 编辑文档
     */
    public function edit()
    {
        if (request()->isAjax()) {
            $param = get_params();
            try {
                validate(CaseDocCheck::class)->check($param);
                $this->model->edit($param);
            } catch (ValidateException $e) {
                return to_assign(1, $e->getError());
            }
        }
        $id = input('id', 0);
        $detail = $this->model->getDoc($id);
        if ($detail['code'] !== 0) {
            return to_assign(1, $detail['msg']);
        }
        View::assign([
            'id' => $id,
            'detail' => $detail['data']
        ]);
        return view('add');
    }

    /**
     * 删除文档
     */
    public function delete()
    {
        $id = get_params("id");
        return json($this->model->remove($id));
    }
}